package com.poetize.plus.controller.admin;

import com.poetize.plus.handler.LoginSuccessHandler;
import com.poetize.plus.service.impl.UserDetailsServiceImpl;
import com.poetize.plus.utils.JwtUtil;
import com.poetize.plus.utils.R;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zuosy
 * @created 2024/3/28 16:55
 */
@Tag(name = "认证管理")
@RestController
@RequestMapping
@RequiredArgsConstructor
public class SecurityController {

    private final JwtUtil jwtUtil;

    private final RedisTemplate<String, Object> redisTemplate;

    private final LoginSuccessHandler loginSuccessHandler;

    private final UserDetailsServiceImpl userDetailsService;

    @PermitAll
    @GetMapping("/refreshToken")
    @Operation(summary = "刷新token")
    public R<String> refreshToken(HttpServletRequest request){
        String header = request.getHeader("Authorization");
        if (StringUtils.hasText(header)){
            Object cacheObject = redisTemplate.opsForValue().get("refresh_token:" + header);
            if (Objects.nonNull(cacheObject)){
                String token = cacheObject.toString();
                Claims claims = jwtUtil.parseClaims(token);
                String username = claims.get("username").toString();
                UserDetails user = userDetailsService.loadUserByUsername(username);
                String newToken = loginSuccessHandler.genToken(user.getUsername());
                //删除旧的refresh_token
                redisTemplate.delete("refresh_token:" + header);
                return R.ok(newToken);
            }
        }
        return R.fail();
    }
}
